<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\User;
use App\Models\Organization;
use Illuminate\Support\Facades\DB;

class OrganizationUserSeeder extends Seeder
{
    /**
     * Run the database seeds.
     * 模拟用户与组织的关联数据
     */
    public function run(): void
    {
        // 获取所有用户和组织
        $users = User::all();
        $organizations = Organization::all();
        
        if ($users->isEmpty() || $organizations->isEmpty()) {
            $this->command->info('没有找到用户或组织数据，请先运行其他 Seeder');
            return;
        }
        
        // 清空现有的用户-组织关联数据
        DB::table('organization_user')->truncate();
        
        // 为每个用户随机分配1-3个组织
        foreach ($users as $user) {
            // 随机选择1-3个组织
            $randomOrgs = $organizations->random(rand(1, min(3, $organizations->count())));
            
            foreach ($randomOrgs as $org) {
                // 20%的概率成为管理员
                $isAdmin = (rand(1, 5) === 1);
                
                // 添加用户到组织
                DB::table('organization_user')->insert([
                    'organization_id' => $org->id,
                    'user_id' => $user->id,
                    'is_admin' => $isAdmin,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
            }
        }
        
        // 确保至少有一个用户是总公司的管理员
        $hqOrg = $organizations->where('code', 'HQ')->first();
        if ($hqOrg) {
            $adminUser = $users->first();
            
            // 检查是否已经存在关联
            $exists = DB::table('organization_user')
                ->where('organization_id', $hqOrg->id)
                ->where('user_id', $adminUser->id)
                ->exists();
            
            if ($exists) {
                // 更新为管理员
                DB::table('organization_user')
                    ->where('organization_id', $hqOrg->id)
                    ->where('user_id', $adminUser->id)
                    ->update(['is_admin' => true]);
            } else {
                // 添加为管理员
                DB::table('organization_user')->insert([
                    'organization_id' => $hqOrg->id,
                    'user_id' => $adminUser->id,
                    'is_admin' => true,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
            }
        }
        
        $this->command->info('用户与组织关联数据已生成！');
    }
}
